// router/index.ts
import { createWebHistory, createRouter, RouteRecordRaw, RouteLocationNormalized } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';

// 静态路由（所有用户都可访问）
export const constantRoutes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/views/index.vue'),
    redirect: '/home',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/index.vue'),
        meta: { title: '首页', requiresAuth: true }
      },
      {
        path: 'piece',
        name: 'Piece',
        component: () => import('@/views/myPiece/index.vue'),
        meta: { title: '我的文章', requiresAuth: true }
      },
      {
        path: 'addArticle',
        name: 'CreateArticle',
        component: () => import('@/views/myPiece/addArticle.vue'),
        meta: { 
          title: '创建文章', 
          requiresAuth: true
          // permission: 'article:create'
        }
      },
      {
        path: 'editArticle/:id',
        name: 'EditArticle',
        component: () => import('@/views/myPiece/editArticle.vue'),
        meta: { 
          title: '编辑文章', 
          requiresAuth: true
          // permission: 'article:edit'
        }
      },
      {
        path: 'collections',
        name: 'Collections',
        component: () => import('@/views/collections/index.vue'),
        meta: { 
          title: '我的收藏', 
          requiresAuth: true
          // permission: 'collection:view'
        }
      },
      {
        path: 'articleDetail/:id/:type?',
        name: 'ArticleDetail',
        component: () => import('@/views/myPiece/articleDetail.vue'),
        meta: { 
          title: '文章详情', 
          requiresAuth: true
          // permission: 'article:view'
        }
      },
      {
        path: 'friends',
        name: 'Friends',
        component: () => import('@/views/friends/index.vue'),
        meta: { title: '粉丝与关注', requiresAuth: true }
      },
      {
        path: 'personalStatistics',
        name: 'PersonalStatistics',
        component: () => import('@/views/statistics/index.vue'),
        meta: { 
          title: '个人统计', 
          requiresAuth: true
          // permission: 'article:view'
        }
      },
      {
        path: 'system',
        name: 'System',
        redirect: '/system/contentManagement',
        meta: { 
          title: '系统管理', 
          requiresAuth: true,
          // permission: 'system:manage',
          icon: 'setting'
        },
        children: [
          {
            path: 'contentManagement',
            name: 'ContentManagement',
            component: () => import('@/views/system/contentManagement/index.vue'),
            meta: { 
              title: '内容管理', 
              requiresAuth: true
              // permission: 'content:manage'
            }
          },
          {
            path: 'userManagement',
            name: 'UserManagement',
            component: () => import('@/views/system/userManagement/index.vue'),
            meta: { 
              title: '用户管理', 
              requiresAuth: true,
              // permission: 'user:manage',
              roles: ['admin']
            }
          }
        ]
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '页面不存在', requiresAuth: false }
  }
];

// 动态路由（根据权限动态添加）
export const asyncRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: () => import('@/views/index.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'addArticle',
        name: 'CreateArticle',
        component: () => import('@/views/myPiece/addArticle.vue'),
        meta: { 
          title: '创建文章', 
          requiresAuth: true,
          permission: 'article:create'
        }
      },
      {
        path: 'editArticle/:id',
        name: 'EditArticle',
        component: () => import('@/views/myPiece/editArticle.vue'),
        meta: { 
          title: '编辑文章', 
          requiresAuth: true,
          permission: 'article:edit'
        }
      },
      {
        path: 'collections',
        name: 'Collections',
        component: () => import('@/views/collections/index.vue'),
        meta: { 
          title: '我的收藏', 
          requiresAuth: true,
          permission: 'collection:view'
        }
      },
      {
        path: 'articleDetail/:id/:type?',
        name: 'ArticleDetail',
        component: () => import('@/views/myPiece/articleDetail.vue'),
        meta: { 
          title: '文章详情', 
          requiresAuth: true,
          permission: 'article:view'
        }
      },
      {
        path: 'system',
        name: 'System',
        redirect: '/system/contentManagement',
        meta: { 
          title: '系统管理', 
          requiresAuth: true,
          permission: 'system:manage',
          icon: 'setting'
        },
        children: [
          {
            path: 'contentManagement',
            name: 'ContentManagement',
            component: () => import('@/views/system/contentManagement/index.vue'),
            meta: { 
              title: '内容管理', 
              requiresAuth: true,
              permission: 'content:manage'
            }
          },
          {
            path: 'userManagement',
            name: 'UserManagement',
            component: () => import('@/views/system/userManagement/index.vue'),
            meta: { 
              title: '用户管理', 
              requiresAuth: true,
              permission: 'user:manage',
              roles: ['admin']
            }
          }
        ]
      }
    ]
  }
];

// 创建路由器实例
const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
});

// 路由守卫更新
router.beforeEach(async(to: RouteLocationNormalized, from, next) => {
  const userStore = useUserStore();
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 我的系统`;
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (!userStore.isAuthenticated) {
      // 未登录，跳转到登录页
      ElMessage.warning('请先登录');
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
      return;
    }

    // 使用store中的方法检查权限
    if (!userStore.hasRoutePermission(to.meta)) {
      ElMessage.error('没有访问权限');
      next(from.fullPath || '/home');
      return;
    }
  }

  // 如果已经登录且访问登录页，跳转到首页
  if (to.path === '/login' && userStore.isAuthenticated) {
    next(from.query.redirect as string || '/home');
    return;
  }

  next();
});

// 动态添加路由的方法
export const addRoutes = (routes: RouteRecordRaw[]) => {
  routes.forEach(route => {
    if (!router.hasRoute(route.name!)) {
      router.addRoute(route);
    }
  });
};

// 动态路由过滤更新
export const filterAsyncRoutes = (routes: RouteRecordRaw[]): RouteRecordRaw[] => {
  const userStore = useUserStore();
  
  return routes.filter(route => {
    // 使用store中的方法检查权限
    if (!userStore.hasRoutePermission(route.meta)) {
      return false;
    }

    // 递归处理子路由
    if (route.children) {
      route.children = filterAsyncRoutes(route.children);
    }

    return true;
  });
};

// 初始化动态路由
export const initDynamicRoutes = async() => {
  const userStore = useUserStore();
  
  if (!userStore.isAuthenticated) {
    return;
  }

  // 获取用户权限信息（这里可以根据实际情况从API获取）
  // const userPermissions = userStore.permissions || [];
  // const userRoles = userStore.roles || [];

  // 过滤动态路由
  // const accessibleRoutes = filterAsyncRoutes(asyncRoutes, userPermissions, userRoles);
  const accessibleRoutes = filterAsyncRoutes(asyncRoutes);
  
  // 添加动态路由
  addRoutes(accessibleRoutes);
};

export default router;